package com.lanxin.realm;

import com.lanxin.dao.UserRoleDao;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by cyh on 2021/3/18.
 */

@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserRoleDao userRoleDao;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String)authenticationToken.getPrincipal();
        String password = userRoleDao.findPasswordByUsername(username);
        if(password!=null){
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,"customrealm");
            authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("lanxin"));
            return authenticationInfo;
        }
        return null;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userRoleDao.findRolesByUsername(username));
        authorizationInfo.setStringPermissions(userRoleDao.findPerssionByUsername(username));

        return authorizationInfo;
    }
}
